package com.tc.have_a_tired.ui;

import javax.swing.*;
import java.awt.*;

/**
 * 自定义彩色按钮类
 * 确保背景颜色在所有Look and Feel下都能正确显示
 */
public class ColoredButton extends JButton {

    private Color hoverColor;
    private Color normalColor;

    public ColoredButton(String text) {
        super(text);
        setFocusPainted(false);
        setBorderPainted(false);
        setContentAreaFilled(false);
        setOpaque(true);
    }

    public ColoredButton(String text, Color backgroundColor, Color foregroundColor) {
        this(text);
        setBackground(backgroundColor);
        setForeground(foregroundColor);
        this.normalColor = backgroundColor;
    }

    public ColoredButton(String text, Color backgroundColor, Color foregroundColor, Color hoverColor) {
        this(text, backgroundColor, foregroundColor);
        this.hoverColor = hoverColor;

        // 添加悬停效果
        addMouseListener(new java.awt.event.MouseAdapter() {
            @Override
            public void mouseEntered(java.awt.event.MouseEvent e) {
                if (ColoredButton.this.hoverColor != null) {
                    setBackground(ColoredButton.this.hoverColor);
                }
            }

            @Override
            public void mouseExited(java.awt.event.MouseEvent e) {
                if (ColoredButton.this.normalColor != null) {
                    setBackground(ColoredButton.this.normalColor);
                }
            }
        });
    }

    @Override
    protected void paintComponent(Graphics g) {
        // 强制绘制背景颜色
        if (getModel().isPressed()) {
            g.setColor(getBackground().darker());
        } else if (getModel().isRollover() && hoverColor != null) {
            g.setColor(hoverColor);
        } else {
            g.setColor(getBackground());
        }
        g.fillRect(0, 0, getWidth(), getHeight());

        // 绘制文本
        super.paintComponent(g);
    }

    @Override
    public void setBackground(Color bg) {
        super.setBackground(bg);
        if (normalColor == null || !getModel().isRollover()) {
            normalColor = bg;
        }
    }
}
